package com.jweb.framework.security.data.safe;

import java.io.UnsupportedEncodingException;

import com.jweb.framework.security.crypto.cipher.symmetric.DefaultSymCipherer;
import com.jweb.framework.security.crypto.cipher.symmetric.SymCipherer;
import com.jweb.framework.security.crypto.common.ECipherMode;

/**
 * 修改人： Thomas
 * 修改内容：新增 
 * 类说明：
 */
public class DataFieldDecrypt implements IDecrypt {
	
	final byte initKeyBytes[] = {101, 111, 33, -117, -51, -85, 9, 120};

	@Override
	public String getData(String in, String pwd) throws UnsupportedEncodingException {
		
		SymCipherer decrypt = new DefaultSymCipherer(ECipherMode.DECRYPT);
		
		byte[] pwds = this.getPwds(pwd);
		
		byte[] bytes = decrypt.encrypt(initKeyBytes , pwds , asc2bcd(in)) ;
		
		return new String(bytes , "UTF-8");
	}
	
	public byte[] getData(byte[] desBytes , String pwd) {
		SymCipherer decrypt = new DefaultSymCipherer(ECipherMode.DECRYPT);
		
		byte[] pwds = this.getPwds(pwd);
		
		byte[] deBytes = decrypt.encrypt(initKeyBytes , pwds , desBytes);
		
		return deBytes ;
	}
	
	private byte[] getPwds(String pwd) {
		byte[] pwdByte = pwd.getBytes();
		byte[] pwds = new byte[]{0 , 0 , 0 , 0 , 0 , 0 , 0 , 0};
		if(pwdByte.length > 8){
			System.arraycopy(pwdByte , 0 , pwds , 0 , 8);
		}
		else if(pwdByte.length < 8){
			System.arraycopy(pwdByte , 0 , pwds , 0 , pwdByte.length);
		}
		else {
			System.arraycopy(pwdByte , 0 , pwds , 0 , 8);
		}
		
		return pwds ;
	}
	
	private byte[] asc2bcd(String hexstr){
		if (hexstr.length() % 2 != 0){
			hexstr = (new StringBuilder(String.valueOf(hexstr))).append("0").toString();
		}
		byte bytes[] = new byte[hexstr.length() / 2];
		for (int i = 0; i < hexstr.length() / 2; i++) {
			byte temp[] = new byte[2];
			temp[0] = (byte) hexstr.charAt(i * 2);
			temp[1] = (byte) hexstr.charAt(i * 2 + 1);
			bytes[i] = (byte) Integer.parseInt(new String(temp), 16);
		}

		return bytes;
	}

}
